package network;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class UdpEchoClient2 {
    DatagramSocket socket = null;
    String serverIP = "";
    int serverPort = 0;
    UdpEchoClient2(String ip, int port) throws SocketException {
        socket = new DatagramSocket();
        serverIP = ip;
        serverPort = port;
    }

    public void start() throws IOException {
        System.out.println("客户端启动");
        Scanner scanner = new Scanner(System.in);
        while(true) {
            System.out.println("输入-> ");
            String in = scanner.nextLine();
            DatagramPacket sendPacket = new DatagramPacket(in.getBytes(), in.getBytes().length,
                    InetAddress.getByName(serverIP), serverPort);
            socket.send(sendPacket);
            DatagramPacket receivePacket = new DatagramPacket(new byte[4096], 4096);
            socket.receive(receivePacket);
            String ans = new String(receivePacket.getData(), 0, receivePacket.getLength());
            System.out.println(ans);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient2 client2 = new UdpEchoClient2("127.0.0.1", 520);
        client2.start();
    }
}
